extends Node

var definitions = {}

signal build

func _ready():
	var prefix = "res://data/item"
	load_all_definitions(prefix)
	
func load_all_definitions(prefix):
	var dir = Directory.new()
	if dir.open(prefix) != OK:
		printerr("FAILED TO OPEN ITEMS")
		return
	dir.list_dir_begin()
	var file_name = dir.get_next()
	while file_name != "":
		if dir.current_is_dir():
			load_item_dir(prefix, file_name)
		else:
			print("Found unrelated file: " + file_name)
		file_name = dir.get_next()
	emit_signal("build")

func load_item_dir(prefix, dir_name):
	var dir = Directory.new()
	if dir.open(prefix + "/" + dir_name) != OK:
		printerr("FAILED TO OPEN ITEM " + dir_name)
		return
	dir.list_dir_begin()
	var file_name = dir.get_next()
	while file_name != "":
		if dir.current_is_dir():
			pass
		else:
			if file_name.ends_with(".tres"):
				var resource : Item_definition = load(prefix + "/" + dir_name + "/" + file_name)
				var file_prefix = prefix + "/" + dir_name + "/" + file_name.substr(0,file_name.length()-5)
				register_item(file_prefix, resource)
		file_name = dir.get_next()

func register_item(prefix, resource):
	resource.prefix = prefix
	definitions[resource.id] = resource
